package lg.minecraft.plugin.pokemonmenu.tasks;

import lg.minecraft.plugin.pokemonmenu.LGPokemonMenu;
import lg.minecraft.plugin.pokemonmenu.gui.PInventory;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author langle__
 * @version 1.0
 */
public class InventoryRealTimeUpdate extends BukkitRunnable {

    private final Map<Player, PInventory> map = new HashMap<>();

    private BukkitTask task;

    public void start() {
        if (task != null) task.cancel();
        task = runTaskTimer(LGPokemonMenu.getInstance(), 30, 30);
    }

    public void stop() {
        if (task != null) {
            task.cancel();
            task = null;
        }
    }

    @Override
    public void run() {
        if (map.isEmpty()) return;
        Iterator<Map.Entry<Player, PInventory>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Player, PInventory> entry = iterator.next();
            Player player = entry.getKey();
            PInventory inventory = entry.getValue();
            if (player.isOnline()) {
                inventory.onDrawInventory(player);
            } else {
                iterator.remove(); // 安全删除
            }
        }
    }

    public void addPlayer(Player player, PInventory inventory) {
        if (task == null) return;
        map.put(player, inventory);
    }

    public void removePlayer(Player player) {
        map.remove(player);
    }

    public void canStart() {
        if (LGPokemonMenu.getMainConfig().isRealTimeUpdate()) start();
    }

}
